<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-button v-if="hasRoles(['COMPANY_CONTRACT_MGMT', 'SUPER_ADMIN'])" class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">{{$t('table.add')}}</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column fixed="left" :label="$t('table.contract_name')"  width="200px" >
        <template slot-scope="scope">
          <el-tag>{{scope.row.contract_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.start_date')"  width="100px"  >
        <template slot-scope="scope">
          {{scope.row.start_date| timeFilter('{y}-{m}-{d}') }}
        </template>
      </el-table-column>
       <el-table-column :label="$t('table.end_date')"  width="100px"  >
        <template slot-scope="scope">
          {{scope.row.end_date| timeFilter('{y}-{m}-{d}') }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.guarantee_period')"  width="100px"  >
        <template slot-scope="scope">
          {{scope.row.guarantee_period| guaranteePeriodValFilter }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.invoice_title')"  width="150px" >
        <template slot-scope="scope">
          {{scope.row.invoice_title }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.charge_standard')"  width="200px" >
        <template slot-scope="scope">
        {{scope.row.charge_standard }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.contract_comment')"  width="200px" >
        <template slot-scope="scope">
        {{scope.row.contract_comment }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" :label="$t('table.actions')"  class-name="small-padding fixed-width" min-width="200px">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" v-if="hasRoles(['COMPANY_CONTRACT_MGMT', 'SUPER_ADMIN'])" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
          <el-button type="primary" size="mini" v-if="hasRoles(['COMPANY_CONTRACT_MGMT', 'SUPER_ADMIN'])"  @click="download(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[contractDialogStatus]" :visible.sync="contractDialogVisible" append-to-body>
      <el-form  :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item :label="$t('table.contract_name')" prop="contract_name">
          <el-input v-model="temp.contract_name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('table.date_range')" prop="start_date">
            <el-date-picker
              v-model="temp.date_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd" value-format="timestamp" 
              >
            </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('table.guarantee_period')" prop="guarantee_period">
          <el-select class="filter-item" v-model="temp.guarantee_period" placeholder="Please select">
            <el-option v-for="item in guaranteePeriodOptions " :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.invoice_title')" prop="invoice_title">
          <el-input v-model="temp.invoice_title"></el-input>
        </el-form-item>
         <el-form-item :label="$t('table.charge_standard')" prop="charge_standard">
          <el-input type="textarea" :rows="4" v-model="temp.charge_standard"></el-input>
        </el-form-item>
        <el-form-item label="BD" prop="bd">
          <el-select
          v-model="temp.bd"
          filterable
          clearable
          collapse-tags
          placeholder="请选择">
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件上传" prop="department_type">
          <el-upload
              class="upload-demo"
              action="/api/upload/attachment"
              :data="attachment_temp"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :before-remove="beforeRemove"
              :on-success="uploadSuccess"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList">
              <el-button icon='el-icon-upload' size="small" plain>上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload> 
        </el-form-item>
        <el-form-item :label="$t('table.contract_comment')" prop="contract_comment">
          <el-input type="textarea" :rows="4" v-model="temp.contract_comment"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="contractDialogVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="contractDialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import API from '@/utils/backend_api'
import Static_Data from '@/data/index'
import waves from '@/directive/waves' // 水波纹指令
import { getToken } from '@/utils/auth'
export default {
  name: 'companyContract',
  props: {
    id: {
      type: String,
      default: '' // 这样可以指定默认的值
    }
  },
  directives: {
    waves
  },
  data() {
    return {
      userOptions: this.$store.getters.usersList.map(item => ({ value: item.id, label: item.username + '(' + item.uid + ')' })),
      current_user_id: this.$store.getters.userId,
      current_user_roles: this.$store.getters.roles,
      contractDialogVisible: false,
      contractDialogStatus: '',
      guaranteePeriodOptions: Static_Data.guarantee_period,
      textMap: {
        update: '编辑合同',
        create: '新增合同'
      },
      tableKey: 0,
      list: null,
      total: null,
      listLoading: false,
      rules: {
        // degree: [{ required: true, message: 'degree is required', trigger: 'change' }]
        // // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        // title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      temp: {
        contract_name: '',
        start_date: '',
        end_date: '',
        date_range: [],
        guarantee_period: '',
        invoice_title: '',
        charge_standard: '',
        contract_comment: '',
        bd: '',
        attachment_path: '',
        attachment_name: ''
      },
      fileList: [],
      attachment_temp: {
        folder: 'contract'
      },
      headers: {
        Authorization: getToken(),
        smail: '*_~'
      }
    }
  },
  filters: {
  },
  created() {
    this.getList()
  },
  watch: {
    id: function(val, oldVal) {
      console.log('当前值为：' + val, '旧值为：' + oldVal)
      if (val && val !== '') {
        this.getList()
      }
    }
  },
  methods: {
    download(row) {
      API.company_contract.attachment(row.company_id, row.id).then(response => {
        var fileDownload = require('downloadjs')
        fileDownload(response.data, row.attachment_name)
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning('当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件')
    },
    beforeRemove(file, fileList) {
      return this.$confirm('确定移除 ${ file.name }?')
    },
    uploadSuccess(response, file, fileList) {
      console.log(response)
      if (response.path && response.name) {
        this.temp.attachment_path = response.path
        this.temp.attachment_name = response.name
      }
    },
    beforeUpload(file) {
      if (this.attachment_temp && this.attachment_temp.folder && this.attachment_temp.folder !== '') {
        return true
      } else {
        this.$message.warning('文件夹不能为空')
        return false
      }
    },
    hasRoles(roles) {
      return this.current_user_roles.some(item => roles.indexOf(item) >= 0)
    },
    resetTemp() {
      this.temp = {
        contract_name: '',
        start_date: '',
        end_date: '',
        date_range: [],
        guarantee_period: '',
        invoice_title: '',
        charge_standard: '',
        contract_comment: '',
        bd: '',
        attachment_path: '',
        attachment_name: ''
      }
    },
    getList() {
      if (this.id && this.id !== '') {
        this.listLoading = true
        API.company_contract.all(this.id).then(response => {
          this.list = response.data
          if (response.headers && response.headers['x-total-count']) {
            this.total = Number(response.headers['x-total-count'])
          }
          this.listLoading = false
        })
      }
    },
    handleCreate() {
      this.resetTemp()
      this.contractDialogStatus = 'create'
      this.contractDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.date_range = [this.temp.start_date, this.temp.end_date]
      this.contractDialogStatus = 'update'
      this.contractDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.start_date = this.temp.date_range[0]
          this.temp.end_date = this.temp.date_range[1]
          API.company_contract.add(this.id, this.temp).then((response) => {
            console.log(response)
            this.list.unshift(response.data)
            this.contractDialogVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          API.company_contract.update(this.id, tempData).then((response) => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, response.data)
                break
              }
            }
            this.contractDialogVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }
  }
}
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>